package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.crypto.digest.BCrypt;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.SuperConstant;
import com.zzyl.dto.UserDto;
import com.zzyl.entity.User;
import com.zzyl.entity.UserRole;
import com.zzyl.enums.BasicEnum;
import com.zzyl.exception.BaseException;
import com.zzyl.mapper.UserMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.UserService;
import com.zzyl.vo.RoleVo;
import com.zzyl.vo.UserVo;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import java.util.stream.Collectors;

@Service
@Transactional
public class UserServiceImpl implements UserService {
    @Autowired
    private UserMapper userMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    /**
     * 用户分页
     *
     * @param userDto
     * @param pageNum
     * @param pageSize
     * @return
     */
    @Override
    public PageResponse<UserVo> list(UserDto userDto, int pageNum, int pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        Page<UserVo> page = userMapper.selectByPage(userDto);
        return PageResponse.of(page, UserVo.class);
    }

    /**
     * 用户添加
     *
     * @param userDto
     * @return
     */
    @Override
    public Boolean createUser(UserDto userDto) throws CloneNotSupportedException {
        //1.把dto转换为pojo
        User user = userDto.clone();
        user.setUpdateTime(LocalDateTime.now());
        user.setCreateTime(LocalDateTime.now());
        user.setCreateBy(1668522280851951617L);
        user.setPassword(BCrypt.hashpw("123456", BCrypt.gensalt()));
        user.setDataState(SuperConstant.DATA_STATE_0);
        userMapper.insert(user);

        Set<String> roleVoIds = userDto.getRoleVoIds();
        //把set集合转换为list集合
        List<String> roleIdList = new ArrayList<>(roleVoIds);
        //定义一个中间表集合
        List<UserRole> list = new ArrayList<>();
        //遍历集合为集合初始化
        roleIdList.stream().map(r -> {
            //声明一个中间表对象
            UserRole userRole = new UserRole();
            userRole.setUpdateTime(LocalDateTime.now());
            userRole.setCreateTime(LocalDateTime.now());
            userRole.setRoleId(Long.parseLong(r));
            userRole.setUserId(user.getId());
            list.add(userRole);
            return list;
        }).collect(Collectors.toList());

        //批量新增用户和角色中间表
        Boolean flag = userRoleMapper.insertBatch(list);
        return flag;
    }

    /**
     * 用户修改
     *
     * @param userDto
     * @return
     */
    @Override
    public Boolean update(UserDto userDto) throws CloneNotSupportedException {
        User user = userDto.clone();
        user.setUpdateTime(LocalDateTime.now());
        user.setCreateTime(LocalDateTime.now());
        user.setUpdateBy(1671403256519078138L);
        userMapper.update(user);

        //删除用户相关角色信息
        if (null != userDto.getRoleVoIds() && userDto.getRoleVoIds().size() != 0) {
            userMapper.deleteByUserId(userDto.getId());
        }
        //定义一个中间表集合添加角色的相关信息
        Set<String> roleVoIds = userDto.getRoleVoIds();
        List<String> roleList = new ArrayList<>(roleVoIds);
        List<UserRole> list = new ArrayList<>();

        roleList.stream().map(r -> {
            UserRole userRole = new UserRole();
            userRole.setUpdateTime(LocalDateTime.now());
            userRole.setCreateTime(LocalDateTime.now());
            userRole.setRoleId(Long.parseLong(r));
            userRole.setUserId(user.getId());
            list.add(userRole);
            return list;
        }).collect(Collectors.toList());

        Boolean flag = userRoleMapper.insertBatch(list);
        return flag;
    }

    /**
     * 启用禁用
     *
     * @param id
     * @param status
     */
    @Override
    public Boolean updateStatus(Long id, String status) {
//        User user = new User();
//        user.setId(id);
//        user.setDataState(status);
        User user = userMapper.getById(id);
        user.setUpdateTime(LocalDateTime.now());
        user.setDataState(status);
        Boolean flag = userMapper.update(user);
        return flag;
    }

    /**
     * 删除用户
     *
     * @param userIds
     */
    @Override
    public Boolean delete(Long userIds) {
        User user = userMapper.getById(userIds);
        if (user.getDataState().equals(SuperConstant.DATA_STATE_0)) {
            throw new BaseException(BasicEnum.PANRENT_ROLE_STATUS);
        }
        user.setUpdateTime(LocalDateTime.now());
        user.setIsDelete(Integer.valueOf(SuperConstant.DATA_STATE_1));
        Boolean flag = userMapper.update(user);
        return flag;
    }

    /**
     * 密码重置
     *
     * @param userId
     * @return
     */
    @Override
    public Boolean updatePassword(Long userId) {
        User user = userMapper.getById(userId);
        user.setUpdateTime(LocalDateTime.now());
        Boolean flag = userMapper.update(user);
        return flag;
    }

    /**
     * 用户列表
     *
     * @param userDto
     * @return
     */
    @Override
    public List<UserVo> findList(UserDto userDto) throws CloneNotSupportedException {
        User user = userDto.clone();
        user.setUpdateTime(LocalDateTime.now());
        user.setId(userDto.getId());
        return userMapper.findAll(user);
    }
}
